import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom'
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Modal ,Tooltip} from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import { openNotification_util, checkdatavalid_util, fetchsync_util, useCallbackState, dealnullorundenfined } from '../util/util.js'
import { useLatest } from 'ahooks';
const { Search } = Input;
var storage = window.localStorage;

const Popup_table_hooks_transfer = (props) => {
  const history = useHistory();
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [selectedRowsmx, setselectedRowsmx] = useState([])
  const [selectedRowKeysmx, setselectedRowKeysmx] = useState([])
  const [mxdata, setmxdata] = useState(props.datas_mx)
  const [tabledata, settabledata] = useState([])
  const [filterdata, setfilterData] = useState([])
  const [viewname, setviewname] = useState(props.viewname)
  const [viewmxname, setviewmxname] = useState(props.viewmxname)
  const [inputvalue, setinputvalue] = useState(props.inputvalue)
  const [ifshow, setifshow] = useState(false)
  const [isExactMatch, setIsExactMatch] = useState(false);
  const isExactMatchRef = useLatest(isExactMatch);
  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setselectedRows(selectedRows)
      setselectedRowKeys(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };
  const rowSelectionmx = {
    selectedRowKeys: selectedRowKeysmx,
    onChange: (selectedRowKeysmx, selectedRowsmx) => {
      setselectedRowsmx(selectedRowsmx)
      setselectedRowKeysmx(selectedRowKeysmx)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };


  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(false);
  };

  const handleSearchExact = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(true);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        // //console.log(selectedRowKeys)
      }
    }
  };

  const getColumnSearchProps = (dataIndex, style, rendertype, ifcolor, title, searchtype) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 16,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >

        {
          //根据类型选择input、select或list列表模式

          searchtype == "select" ?

            <Select
              ref={searchInput}
              mode="multiple"
              showSearch
              placeholder={`搜索${title}`}
              onChange={(value) => setSelectedKeys(value)}
              onSearch={(value) => setSelectedKeys(value ? [value] : [])}
              onClear={() => {
                setSelectedKeys([]);
                clearFilters();
              }}
              allowClear
              style={{
                width: '20vw',
                marginBottom: 8,
                display: 'block',
              }}
            >
              {[...new Set(props.tabledata.map(item => item[dataIndex]))].map((value) => (
                <Select.Option key={value} value={value}>
                  {value}
                </Select.Option>
              ))}
            </Select>
            :
            <Input
              ref={searchInput}
              placeholder={`搜索${title}`}
              value={selectedKeys[0]}
              onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
              style={{
                marginBottom: 8,
                display: 'block',
              }}
            />

        }

        <Space style={{zIndex:9999}}>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,

            }}
          >
            搜索
          </Button>
          <Button
            type="primary"
            onClick={() => handleSearchExact(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,

            }}
          >
            精准搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}

            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
          {/* <Checkbox onChange={(e)=>{setIsExactMatch(e.target.checked)}} value={isExactMatch}>精准匹配</Checkbox> */}
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      searchtype == "select" ?
        <FilterOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
        :
        <SearchOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
    ),
    onFilter: (value, record) => {
      if (searchtype == "select") {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      }
      else if (isExactMatchRef.current) {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      }
      else {
        return record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
      }
    },
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) => {
      const renderContent = (text, rendertype) => {
        // 处理图片渲染
        if (rendertype === "img") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无图片</span>
              </div>
            );
          }

          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black", display: "flex", flexDirection: "row" }}>
              <RcViewer options={{ toolbar: 1 }}>
                {text.split(',').map((item, index) => (
                  <div key={index} style={{ width: "4vw", height: "4vw", position: 'relative', marginLeft: "0.1vw", display: "inline-block" }}>
                    <img
                      style={{ width: "90%", left: "0", position: "absolute", right: "0", top: "0", bottom: "0", margin: "auto" }}
                      src={`http://111.77.154.58:2233/${item}`}
                      alt=""
                    />
                  </div>
                ))}
              </RcViewer>
            </div>
          );
        }

        // 处理URL渲染
        if (rendertype === "url") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无附件</span>
              </div>
            );
          }

          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
              {text.split(',').map((item, index) => (
                <div key={index} style={{ position: 'relative' }}>
                  <a
                    style={{ color: "#0885fb" }}
                    href={`http://111.77.154.58:2233/${item}`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    附件{index + 1}
                  </a>
                </div>
              ))}
            </div>
          );
        }

        // 处理普通文本渲染
        if (searchedColumn === dataIndex) {
          return (
            <Highlighter
              highlightStyle={{
                backgroundColor: '#ffc069',
                padding: 0,
              }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          );
        }

        return (
          <span style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
            <Tooltip title={text}>
              <span style={style ? style : {}}>{text}</span>
            </Tooltip>
          </span>
        );
      };

      return renderContent(text, rendertype);

    },

  });

  const colnumsorigin = props.tablecolnum
  const columns = colnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),

    }
  })
  const mxcolnumsorigin = props.mxtablecolnum
  const mxcolumns = mxcolnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),

    }
  })



  useEffect(() => {
    setinputvalue(props.inputvalue)
  }, [props.inputvalue])

  const clearMxdata = (tabledata, mxdata) => {
    for (let i = 0; i < tabledata.length; i++) {
      let fieldValue = tabledata[i].cdbh   // 获取当前行的特定字段值

      if (mxdata.some(item => item.cdqx === fieldValue)) {
        tabledata.splice(i, 1);  // 如果当前行的特定字段值在第二个数组中找到了匹配项，则从第一个数组中删除该行
        i--; // 调整索引，因为删除了一个元素
      }
    }
    for (let i = 0; i < tabledata.length; i++) {
      tabledata[i].xuhao = i + 1
    }
    return tabledata;
  }
  const noneMxdata = (mxdata) =>{
    mxdata = mxdata.filter((item) => item.cdqx !== "");
    return mxdata;
  }


  useEffect(() => {
    console.log("props.datas", props.datas.length);
    
    settabledata(dealnullorundenfined(props.datas))
    setmxdata(noneMxdata(dealnullorundenfined(props.datas_mx)))
    setfilterData(clearMxdata(dealnullorundenfined(props.datas), dealnullorundenfined(props.datas_mx)))
  }, [props.datas, props.datas_mx])


  useEffect(() => {
    setselectedRowKeys([])
    setselectedRows([])
    setfilterData(clearMxdata(dealnullorundenfined(props.datas), dealnullorundenfined(props.datas_mx)))
  }, [ifshow])


  //送回数据
  const sendbackdata = async () => {
    if (mxdata.length == 0) { openNotification_util("未选择数据") }
    else {
      props.handlechange({ mxdata })
      setifshow(false)
      
    }

  }

  //加入数据
  const addData = async () => {
    if (selectedRows.length == 0) { openNotification_util("未选择数据") }
    else {
      for (let i = 0; i < selectedRows.length; i++) {
        let bhValue = selectedRows[i].cdbh   // 获取当前行的特定字段值
        let mcValue = selectedRows[i].cdmc
        let ssmkValue = selectedRows[i].ssmk
        let jjcdValue = selectedRows[i].jjcd
        let idValue = selectedRows[i].id
        const newRow = {id: idValue, xuhao: mxdata.length + 1, cdqx: bhValue, cdmc: mcValue, ssmk: ssmkValue,jjcd:jjcdValue, key: bhValue };
        mxdata.push(newRow);
        setmxdata([...mxdata])

      }
      for (let i = 0; i < filterdata.length; i++) {
        let fieldValue = filterdata[i].cdbh   // 获取当前行的特定字段值

        if (selectedRows.some(item => item.cdbh === fieldValue)) {
          filterdata.splice(i, 1);  // 如果当前行的特定字段值在第二个数组中找到了匹配项，则从第一个数组中删除该行
          i--; // 调整索引，因为删除了一个元素
        }

      }
      for (let i = 0; i < filterdata.length; i++) {
        filterdata[i].xuhao = i + 1
      }
      setselectedRowKeys([])
      setselectedRows([])

      setfilterData([...filterdata])
    }

  }
  const removeData = async () => {
    if (selectedRowsmx.length == 0) { openNotification_util("未选择数据") }
    else {
      for (let i = 0; i < selectedRowsmx.length; i++) {
        let bhValue = selectedRowsmx[i].cdqx   // 获取当前行的特定字段值
        let mcValue = selectedRowsmx[i].cdmc
        let ssmkValue = selectedRowsmx[i].ssmk
        let jjcdValue = selectedRowsmx[i].jjcd
        let idValue = selectedRowsmx[i].id
        const newRow = {id:idValue, xuhao: filterdata.length + 1, cdbh: bhValue, cdmc: mcValue, ssmk: ssmkValue,jjcd:jjcdValue, key: bhValue };
        filterdata.push(newRow);
        setfilterData([...filterdata])

      }
      for (let i = 0; i < mxdata.length; i++) {
        let fieldValue = mxdata[i].cdqx   // 获取当前行的特定字段值

        if (selectedRowsmx.some(item => item.cdqx === fieldValue)) {
          mxdata.splice(i, 1);  // 如果当前行的特定字段值在第二个数组中找到了匹配项，则从第一个数组中删除该行
          i--; // 调整索引，因为删除了一个元素
        }
      }
      for (let i = 0; i < mxdata.length; i++) {
        mxdata[i].xuhao = i + 1
      }
      setmxdata([...mxdata])
    }

  }

  return (
    <div >
      <Input style={{ width: "95%", backgroundColor: "#F2F7FF" }} placeholder={props.placeholder} value={props.inputvalue} onClick={() => {
        setifshow(true)

      }} />
      <Modal open={ifshow} destroyOnClose={true} width="95vw" footer={null} style={{
        backgroundColor: "rgba(0,0,0,0.8)", height: "100vh", left: "0%", top: "0%", zIndex: "1050"
      }}
        bodyStyle={{ width: "95vw", height: "90vh", marginTop: "5vh", borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)" }}
      >
        <div style={{ position: "relative", backgroundColor: "white", height: "100%", width: "100%", overflowY: "auto", borderRadius: "8px" }}>
          <br />
          <Button style={{ position: "absolute", left: "1vw" }} type="" onClick={() => {
            setifshow(false)
          }}> 关闭</Button>&nbsp;
          <Button style={{ position: "absolute", left: "5vw" }} type="primary" onClick={

            sendbackdata}>返回数据 </Button>&nbsp;<br /><br />

          <Table columns={columns} dataSource={filterdata} style={{ width: "45%", height: "98%", position: "absolute", left: "1vw" }}
            size="small"
            title={() => { return <div style={{ fontWeight: "400", fontSize: "14px", textAlign: "left" }}>{props.popup_maintitle}</div> }}
            onRow={onRowSelect}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            className="custom-table-styles" />

          <Table columns={mxcolumns} 
            dataSource={mxdata} style={{ width: "45%", height: "98%", position: "absolute", right: "1vw", }}
            size="small"
            title={() => { return <div style={{ fontWeight: "400", fontSize: "14px", textAlign: "left" }}>{props.popup_mxtitle}</div> }}
            onRow={onRowSelect}
            rowSelection={{
              type: "checkbox",
              ...rowSelectionmx,
            }}
            className="custom-table-styles" />
          <div style={{ position: 'absolute', left: '44%', width: '10%', height: '98%', textAlign: 'center' }}>
            <div style={{position: 'absolute', top: '40%', width: '10%', height: '98%',left:'28%'}}>
              <Button type="primary" onClick={addData}>加入权限 </Button>&nbsp;
              <Button type="primary" onClick={removeData}>移除权限 </Button>&nbsp;
            </div>
          </div>

        </div>

      </Modal>
    </div>
  )

}


export default Popup_table_hooks_transfer




var styles = {
  maincontainer: { height: "90%", width: "99%", backgroundColor: `#F1F1F1` }
}



